﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;

using System.ComponentModel;
using System.Collections;
using MidwayBattle.Engine;
using MidwayBattle.Models;
using MidwayBattle.Drawing;
using System.Windows.Media.Imaging;
using System.Runtime.InteropServices;
using System.Xml;



namespace MidwayBattle
{



    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        // IN-GAME WINDOWS HANDLERS
        public WindowNewGame Ng { get; set; }
        public WindowLoadPlayer WLoad { get; set; }
        public WindowEditPlayer WEd { get; set; }
        public ConnectionWindow WIns { get; set; }
        public WindowRemovePlayer WRem { get; set; }
        public PlayersWindow PWin;
        // END OF IN-GAME WINDOWS HANDLERS


        // PLACING GENERAL VARS
        private Boolean minesPlacing;
        private int CurrShipSize, CurrShipOrientation, CurrShipType;
        private Boolean ShipIsPlaceable;

        private int minesLeft = CustomDefines.MINES_AMOUNT;

        private int Pl_CarriersLeft = CustomDefines.SHIP_CARRIER_AMOUNT;
        private int Pl_BattleshipsLeft = CustomDefines.SHIP_BATTLESHIP_AMOUNT;
        private int Pl_CruisersLeft = CustomDefines.SHIP_CRUISER_AMOUNT;
        private int Pl_DestroyersLeft = CustomDefines.SHIP_DESTROYER_AMOUNT;
        private int Pl_SubmarinesLeft = CustomDefines.SHIP_SUBMARINE_AMOUNT;

        private int TotalShipsPlaced;
        // END OF PLACING GENERAL VARS



        // MULTIPLAYER GENERAL VARS
        private int gameType;
        private int multi_role;
        private int multi_port;
        private String multi_ip;
        // END OF MULTIPLAYER GENERAL VARS


        // IN-GAME GENERAL VARS
        private int Gm_CarriersLeft, Gm_BattleshipsLeft, Gm_CruisersLeft, Gm_DestroyersLeft, Gm_SubmarinesLeft;
        
        private PlacedShip[] PlayerShips = new PlacedShip[CustomDefines.SHIP_TOTALAMOUNTPERPLAYER];
        private PlacedShip[] AIShips = new PlacedShip[CustomDefines.SHIP_TOTALAMOUNTPERPLAYER];

        public Drawings Painter;

        public ConnectionInfo connectInfo;

        private int CurrentGameMode;
        private Board Board1, Board2;
        // END OF IN-GAME GENERAL VARS


        //TO DEL
        public static String debugString = "";


        // IA & DLL - BEGIN -------------------------------------------------------------------------------
        public struct tp
        {
            public int X;
            public int Y;
        }

        [DllImport("MidwayBattleIA.dll")]
        public static extern int test();

        [DllImport("MidwayBattleIA.dll")]
        public static extern tp test2();

        [DllImport("MidwayBattleIA.dll")]
        public static extern tp test3(tp temp);

        [DllImport("MidwayBattleIA.dll")]
        public static extern int test4(int[] tab);

        [DllImport("MidwayBattleIA.dll")]
        public static extern void test5(int[] tab);

        // IA & DLL - END ---------------------------------------------------------------------------------

//-------------------------------------------------------------------------------------------------------------------
        public MainWindow()
        {

            CurrShipOrientation = CustomDefines.ORIENT_TOBOTTOM;

            Painter = new Drawings();

            
            
            //Painter.SplashScreen();
            InitializeComponent();
            Painter.GenerateGridDefinitions(Player1Grid, Player2Grid);
            Painter.SetBGImages(bgplayer1, bgplayer2);
            Painter.DrawSquares(Player1Grid, Player2Grid, this.square_MouseLeave, this.square_MouseEnter, this.square_MouseWheel, this.square_MouseLeftButtonDown);
            Painter.DrawLegends(GeneralGrid);
            Painter.InitCommandsPanel(CustomDefines.DRAW_COMMANDS_NONE, this.placingBtnsClick, PlayBox, PlaceBox);
            CreateBoards();
            CurrentGameMode = CustomDefines.GAMEMODE_INACTIVE;
            ShipIsPlaceable = false;
            CurrShipType = -1;
            minesPlacing = false;
            TotalShipsPlaced = 0;

            Gm_CarriersLeft = Gm_BattleshipsLeft = Gm_CruisersLeft = Gm_DestroyersLeft = Gm_SubmarinesLeft = 0;

            Painter.SetGameContentVisibility(AbstractGrid, GeneralViewBox, false);
            
            Drawings.SetBoatCursor(this);

        }
//-------------------------------------------------------------------------------------------------------------------
        private void CreateBoards()
        {
            Board1 = new Board();
            Board2 = new Board();
        }

 //-------------------------------------------------------------------------------------------------------------------
        private void placingBtnsClick(object sender, RoutedEventArgs e)
        {

            TagComponentProperties tcp = (TagComponentProperties)(((Button)sender).Tag);

            switch (tcp.identifier)
            {
                // Placement porte-avions
                case Keys.BAT1PLBTN: 
                    CurrShipType = CustomDefines.SHIP_CARRIER;
                    CurrShipSize = CustomDefines.SHIP_CARRIER_SIZE;
                    break;

                // Placement battleship
                case Keys.BAT2PLBTN:
                    CurrShipType = CustomDefines.SHIP_BATTLESHIP;
                    CurrShipSize = CustomDefines.SHIP_BATTLESHIP_SIZE;
                    break;

                // Placement croiseur
                case Keys.BAT3PLBTN:
                    CurrShipType = CustomDefines.SHIP_CRUISER;
                    CurrShipSize = CustomDefines.SHIP_CRUISER_SIZE;
                    break;

                // Placement destroyer
                case Keys.BAT4PLBTN:
                    CurrShipType = CustomDefines.SHIP_DESTROYER;
                    CurrShipSize = CustomDefines.SHIP_DESTROYER_SIZE;
                    break;

                // Placement sous-marin:
                case Keys.BAT5PLBTN:
                    CurrShipType = CustomDefines.SHIP_SUBMARINE;
                    CurrShipSize = CustomDefines.SHIP_SUBMARINE_SIZE;
                    break;

                // Enlever bateaux placés
                case Keys.RESETSHIPBTN:
                    foreach (System.Windows.FrameworkElement fe2 in Player1Grid.Children)
                    {
                        TagComponentProperties tcp2 = (TagComponentProperties)fe2.Tag;
                        if (tcp2 != null && (tcp2.compType == TagComponentProperties.CompTypes.TYPE_SHIP || tcp2.compType == TagComponentProperties.CompTypes.TYPE_UNPLACEABLEWATER))
                        {
                            ((Rectangle)fe2).Opacity = 1;
                            ((Rectangle)fe2).Fill = Brushes.Transparent;
                            tcp2.compType = TagComponentProperties.CompTypes.TYPE_SQUARE;
                            tcp2.identifier = Keys.SQUARE;
                        }
                    }

                    Pl_CarriersLeft = CustomDefines.SHIP_CARRIER_AMOUNT;
                    Pl_BattleshipsLeft = CustomDefines.SHIP_BATTLESHIP_AMOUNT;
                    Pl_CruisersLeft = CustomDefines.SHIP_CRUISER_AMOUNT;
                    Pl_DestroyersLeft = CustomDefines.SHIP_DESTROYER_AMOUNT;
                    Pl_SubmarinesLeft = CustomDefines.SHIP_SUBMARINE_AMOUNT;
                    Painter.EnableShipsButtons(PlaceBox);
                    Painter.SetButtonEnabledStatus(PlaceBox, Keys.RESETSHIPBTN, false);
                    Painter.SetButtonEnabledStatus(PlaceBox, Keys.PLAYBTN, false);
                    TotalShipsPlaced = 0;
                    Painter.UpdateAmountsLabels(PlaceBox, Pl_CarriersLeft, Pl_BattleshipsLeft, Pl_CruisersLeft, Pl_DestroyersLeft, Pl_SubmarinesLeft, minesLeft);
                    CurrShipType = -1;
                    break;

                // Placement mines
                case Keys.PLACEMINESBTN:
                    CurrShipType = -1;
                    CurrShipSize = -1;
                    break;

                // Enlever mines placées
                case Keys.MINRESETBTN:
                    Painter.RemoveMines(Player2Grid, false); // Enlève les mines, affichage ET données
                    minesLeft = CustomDefines.MINES_AMOUNT;
                    Painter.UpdateAmountsLabels(PlaceBox, Pl_CarriersLeft, Pl_BattleshipsLeft, Pl_CruisersLeft, Pl_DestroyersLeft, Pl_SubmarinesLeft, minesLeft);
                    Painter.SetButtonEnabledStatus(PlaceBox, Keys.PLACEMINESBTN, true);
                    Painter.SetButtonEnabledStatus(PlaceBox, Keys.MINRESETBTN, false);
                    Painter.SetButtonEnabledStatus(PlaceBox, Keys.PLAYBTN, false);
                    break;

                // Clic sur "PLAY"
                case Keys.PLAYBTN:
                    CurrentGameMode = CustomDefines.GAMEMODE_ACTIVE_PLAYFIRE;
                    Painter.InitCommandsPanel(CustomDefines.DRAW_COMMANDS_PLAY, this.placingBtnsClick, PlayBox, PlaceBox);
                    Painter.RemoveMines(Player2Grid, true); // Enlève les mines, mais seulement à l'affichage (les données restent intactes)
                    break;

            }

            minesPlacing = (tcp.identifier == Keys.PLACEMINESBTN);
            

            CurrShipOrientation = CustomDefines.ORIENT_TOBOTTOM;

        }
//-------------------------------------------------------------------------------------------------------------------

        private void LoadPlayer_Click(object sender, RoutedEventArgs e)
        {
            WindowLoadPlayer WLoad = new WindowLoadPlayer(this);
            this.WLoad = WLoad;
            WLoad.Show();
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void NewGame_Click(object sender, RoutedEventArgs e)
        {
            WindowNewGame WNG = new WindowNewGame(WLoad, this);
            this.Ng = WNG;
            WNG.Show();
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void Add_Click(object sender, RoutedEventArgs e)
        {
            /*
            ConnectionWindow WIns = new ConnectionWindow(this);
            this.WIns = WIns;
            WIns.Show();
             * */
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void RemovePlayer_Click(object sender, RoutedEventArgs e)
        {
            WindowRemovePlayer WRem = new WindowRemovePlayer(this);
            this.WRem = WRem;
            WRem.Show();
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void EditPlayer_Click(object sender, RoutedEventArgs e)
        {
            WindowEditPlayer WEd = new WindowEditPlayer(this);
            this.WEd = WEd;
            WEd.Show();
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void QuitGame_Click(object sender, RoutedEventArgs e)
        {
            string msg = "Are you sure you want to exit the application ?";
            MessageBoxResult result = MessageBox.Show(msg, "Goodbye", MessageBoxButton.YesNo, MessageBoxImage.Warning);

            if (result == MessageBoxResult.No)
            {
                e.Handled = true;
            }
            else
            {
                Environment.Exit(0);
            }
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void About_Click(object sender, RoutedEventArgs e)
        {
            WindowAbout WA = new WindowAbout();
            WA.Show();

        }
        //-------------------------------------------------------------------------------------------------------------------
        private void MainWindow_Closing(object sender, CancelEventArgs e)
        {
            /*
            string msg = "Are you sure you want to exit the application ?";
            MessageBoxResult result = MessageBox.Show(msg, "Goodbye", MessageBoxButton.YesNo, MessageBoxImage.Warning);

            if (result == MessageBoxResult.No)
            {
                e.Cancel = true;
            }
            else
            {
                Environment.Exit(0);
            }
            */

        }
        //-------------------------------------------------------------------------------------------------------------------
        public void ActivMenuItems()
        {
            this.itemNewGame.IsEnabled = true;
            this.itemOpenGame.IsEnabled = true;
            this.itemSaveGame.IsEnabled = true;
            this.itemDeleteGame.IsEnabled = true;
            this.itemEditPlayer.IsEnabled = true;
            this.itemRemovePlayer.IsEnabled = true;
        }
        //-------------------------------------------------------------------------------------------------------------------
        public void DisableMenuItems()
        {
            this.itemNewGame.IsEnabled = false;
            this.itemOpenGame.IsEnabled = false;
            this.itemSaveGame.IsEnabled = false;
            this.itemDeleteGame.IsEnabled = false;
            this.itemEditPlayer.IsEnabled = false;
            this.itemRemovePlayer.IsEnabled = false;
            this.itemLoadPlayer.IsEnabled = false;
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void square_MouseEnter(object sender, MouseEventArgs e)
        {
            TagComponentProperties tcp = (TagComponentProperties)(((Rectangle)sender).Tag);

            // Placement bateaux (chez soi)
            if (CurrentGameMode == CustomDefines.GAMEMODE_ACTIVE_PLACEMENT && (CurrShipType != -1) 
                && (tcp.compType != TagComponentProperties.CompTypes.TYPE_SHIP) && (tcp.compType != TagComponentProperties.CompTypes.TYPE_UNPLACEABLEWATER)
                && tcp.squareProp.Player == 1 && (CountShipsLeft(CurrShipType) > 0))
            {
                Boolean Success = false;       
                for (int NbAttempts = 0; (Success == false && NbAttempts < 4); NbAttempts++)
                {
                    Success = Painter.TryDrawTemporaryShip(Player1Grid, tcp.squareProp.X, tcp.squareProp.Y, CurrShipSize, CurrShipOrientation);
                    if (!Success) Painter.GotoNextOrientationStep(CustomDefines.WHEEL_HOUR, ref CurrShipOrientation);
                    else ShipIsPlaceable = true;
                }
            }

            // Placement des mines (chez l'adversaire)
            if (CurrentGameMode == CustomDefines.GAMEMODE_ACTIVE_PLACEMENT && (CurrShipType == -1)
                && tcp.squareProp.Player == 2 && minesPlacing && (minesLeft > 0) && (tcp.compType != TagComponentProperties.CompTypes.TYPE_MINE))
            {
                ((Rectangle)sender).Opacity = 0.5;
                ((Rectangle)sender).Fill = Brushes.White;
            }

            // Phase de jeu / tir
            if (CurrentGameMode == CustomDefines.GAMEMODE_ACTIVE_PLAYFIRE)
            {
                //
            }


        }
        //-------------------------------------------------------------------------------------------------------------------
        private void square_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            TagComponentProperties tcp = (TagComponentProperties)((Rectangle)sender).Tag;

            if (CurrentGameMode == CustomDefines.GAMEMODE_ACTIVE_PLACEMENT && tcp.squareProp.X != -1 && tcp.squareProp.Y != -1 && CurrShipType != -1 && CountShipsLeft(CurrShipType) > 0)
            {
                Boolean Success = false;
                int PreviousOrient = CurrShipOrientation;

                if (e.Delta > 0)
                {


                    Painter.GotoNextOrientationStep(CustomDefines.WHEEL_HOUR, ref CurrShipOrientation);
                    
                    for (int NbAttempts = 0; (Success == false && NbAttempts < 4); NbAttempts++)
                    {
                        Success = Painter.TryDrawTemporaryShip(Player1Grid, tcp.squareProp.X, tcp.squareProp.Y, CurrShipSize, CurrShipOrientation);
                        if (Success)
                        {
                            Painter.HideTheRestOfTemporaryShip(Player1Grid, tcp.squareProp.X, tcp.squareProp.Y, CurrShipSize, PreviousOrient);
                            ShipIsPlaceable = true;
                        }
                        else
                        {
                            ShipIsPlaceable = false;
                            Painter.GotoNextOrientationStep(CustomDefines.WHEEL_HOUR, ref CurrShipOrientation);
                        }

                    }
                }
                else
                {
                    Painter.GotoNextOrientationStep(CustomDefines.WHEEL_ANTIHOUR, ref CurrShipOrientation);

                    for (int NbAttempts = 0; (Success == false && NbAttempts < 4); NbAttempts++)
                    {
                        Success = Painter.TryDrawTemporaryShip(Player1Grid, tcp.squareProp.X, tcp.squareProp.Y, CurrShipSize, CurrShipOrientation);
                        if (Success)
                        {
                            Painter.HideTheRestOfTemporaryShip(Player1Grid, tcp.squareProp.X, tcp.squareProp.Y, CurrShipSize, PreviousOrient);
                            ShipIsPlaceable = true;
                        }
                        else
                        {
                            Painter.GotoNextOrientationStep(CustomDefines.WHEEL_ANTIHOUR, ref CurrShipOrientation);
                            ShipIsPlaceable = false;
                        }
                    }
                }
            
            }

        }
        //-------------------------------------------------------------------------------------------------------------------
        private void square_MouseLeave(object sender, MouseEventArgs e)
        {
            ShipIsPlaceable = false;

            TagComponentProperties tcp = (TagComponentProperties)((Rectangle)sender).Tag;
            
            // Suppression de la mise en relief temporaire issue du placement des bateaux
            if (CurrentGameMode == CustomDefines.GAMEMODE_ACTIVE_PLACEMENT && (tcp.squareProp.Player == 1) && ((TagComponentProperties)(((Rectangle)sender).Tag)).compType != TagComponentProperties.CompTypes.TYPE_SHIP)
            {
                ((Rectangle)sender).Opacity = 1;
                ((Rectangle)sender).Fill = Brushes.Transparent;
                Painter.HideTheRestOfTemporaryShip(Player1Grid, tcp.squareProp.X, tcp.squareProp.Y, CurrShipSize, CurrShipOrientation);
             
            }

            // Suppression de la mise en relief temporaire issue du placement des mines
            if (CurrentGameMode == CustomDefines.GAMEMODE_ACTIVE_PLACEMENT && (tcp.squareProp.Player == 2) && minesPlacing && (tcp.compType != TagComponentProperties.CompTypes.TYPE_MINE) )
            {
                ((Rectangle)sender).Opacity = 1;
                ((Rectangle)sender).Fill = Brushes.Transparent;
            }
            
        }
        //-------------------------------------------------------------------------------------------------------------------      
        public void square_MouseLeftButtonDown(object sender, MouseEventArgs e)
        {

            TagComponentProperties tcp = (TagComponentProperties)((Rectangle)sender).Tag;

            // Placement de ses navires dans sa propre grille
            if (CurrentGameMode == CustomDefines.GAMEMODE_ACTIVE_PLACEMENT && ShipIsPlaceable && (CountShipsLeft(CurrShipType) > 0) && CurrShipType != -1 && tcp.squareProp.Player == 1)
            {
                Painter.DrawShip(Player1Grid, tcp.squareProp.X, tcp.squareProp.Y, CurrShipType, CurrShipOrientation, CurrShipSize);
                Board1.PlaceShipInMemory(tcp.squareProp.X, tcp.squareProp.Y, CurrShipOrientation, CurrShipSize);
                PlaceShipInTab(PlayerShips, CustomDefines.PLAYER_HUMAN, tcp.squareProp.X, tcp.squareProp.Y, CurrShipOrientation, CurrShipSize, CurrShipType);

                DecrementAvailableShip(CurrShipType);


                if (Pl_CarriersLeft == CustomDefines.SHIP_CARRIER_AMOUNT - 1 || Pl_BattleshipsLeft == CustomDefines.SHIP_BATTLESHIP_AMOUNT - 1 ||
                    Pl_CruisersLeft == CustomDefines.SHIP_CRUISER_AMOUNT - 1 || Pl_DestroyersLeft == CustomDefines.SHIP_DESTROYER_AMOUNT - 1 ||
                    Pl_SubmarinesLeft == CustomDefines.SHIP_SUBMARINE_AMOUNT - 1) // Au placement du premier bateau,
                    
                    Painter.SetButtonEnabledStatus(PlaceBox, Keys.RESETSHIPBTN, true);       // on active le bouton Reset navires

                TotalShipsPlaced++;

                Painter.UpdateAmountsLabels(PlaceBox, Pl_CarriersLeft, Pl_BattleshipsLeft, Pl_CruisersLeft, Pl_DestroyersLeft, Pl_SubmarinesLeft, minesLeft);

                if (
                    TotalShipsPlaced == (CustomDefines.SHIP_CARRIER_AMOUNT + CustomDefines.SHIP_BATTLESHIP_AMOUNT + CustomDefines.SHIP_CRUISER_AMOUNT + CustomDefines.SHIP_DESTROYER_AMOUNT + CustomDefines.SHIP_SUBMARINE_AMOUNT)
                    && minesLeft == 0
                    )
                { Painter.SetButtonEnabledStatus(PlaceBox, Keys.PLAYBTN, true);  }
            }

            
            // Placement des mines dans la grille adverse
            if (CurrentGameMode == CustomDefines.GAMEMODE_ACTIVE_PLACEMENT && minesPlacing && (minesLeft > 0) && (tcp.squareProp.Player == 2) && tcp.compType != TagComponentProperties.CompTypes.TYPE_MINE)
            {   
                ((Rectangle)sender).Opacity = 1;
                ((Rectangle)sender).Fill = CustomDefines.GRID_PLAC_MINESCOLOR;
                tcp.compType = TagComponentProperties.CompTypes.TYPE_MINE;
                minesLeft--;
                if (minesLeft == 0) Painter.SetButtonEnabledStatus(PlaceBox, Keys.PLACEMINESBTN, false);

                if (minesLeft == CustomDefines.MINES_AMOUNT - 1)
                    Painter.SetButtonEnabledStatus(PlaceBox, Keys.MINRESETBTN, true); // Dès le placement de la première mine, on  active le bouton Reset mines

                Painter.UpdateAmountsLabels(PlaceBox, Pl_CarriersLeft, Pl_BattleshipsLeft, Pl_CruisersLeft, Pl_DestroyersLeft, Pl_SubmarinesLeft, minesLeft);

                if (
                    TotalShipsPlaced == (CustomDefines.SHIP_CARRIER_AMOUNT + CustomDefines.SHIP_BATTLESHIP_AMOUNT + CustomDefines.SHIP_CRUISER_AMOUNT + CustomDefines.SHIP_DESTROYER_AMOUNT + CustomDefines.SHIP_SUBMARINE_AMOUNT)
                    && minesLeft == 0
                    )
                { Painter.SetButtonEnabledStatus(PlaceBox, Keys.PLAYBTN, true); }
            }

            // Phase de tir dans la grille adverse
            if (CurrentGameMode == CustomDefines.GAMEMODE_ACTIVE_PLAYFIRE && tcp.squareProp.Player == 2)
            {
                //MessageBox.Show("SQUARE X = " + CurrSquareX + " Y = " + CurrSquareY + "WIDTH= " + ((Rectangle)sender).ActualWidth + " et HEIGHT =" + ((Rectangle)sender).ActualHeight);
            }


        }
        //-------------------------------------------------------------------------------------------------------------------        
        private void PlaceShipInTab(PlacedShip[] tab, int owner, int xStart, int yStart, int orient, int size, int type)
        {
            // On va dans la bonne zone du tableau (bonne zone + cellule vide)
            int cpt = 0;

            while (cpt < CustomDefines.SHIP_TOTALAMOUNTPERPLAYER && tab[cpt].Type != type && tab[cpt].Status != -1) // Status = -1 car on veut une cellule vide
                cpt++;

            // Dans cette cellule, on met les infos données
            tab[cpt].Length = size;
            tab[cpt].Life = size;
            tab[cpt].Orientation = orient;
            tab[cpt].Owner = owner;
            tab[cpt].Status = CustomDefines.SHIP_STATUS_ALIVE;
            tab[cpt].Type = type;
            tab[cpt].XStart = xStart;
            tab[cpt].YStart = yStart;
        }
        //-------------------------------------------------------------------------------------------------------------------
        private int GetSizeOfSmallestShipAlive()
        {
            int ret;

            if (Gm_DestroyersLeft > 0) ret = CustomDefines.SHIP_DESTROYER_SIZE; // Size = 2
            else if (Gm_SubmarinesLeft > 0 || Gm_CruisersLeft > 0) ret = CustomDefines.SHIP_SUBMARINE_SIZE; // Size = 3
            else if (Gm_BattleshipsLeft > 0) ret = CustomDefines.SHIP_BATTLESHIP_SIZE; // Size = 4
            else ret = CustomDefines.SHIP_CARRIER_SIZE; // Size = 5

            return ret;
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void DecrementAvailableShip(int _type)
        {
            CustomDefines defines = new CustomDefines();

            // décrémenter en mémoire
            switch (_type)
            {
                case CustomDefines.SHIP_CARRIER:
                    Pl_CarriersLeft--;
                    if (Pl_CarriersLeft == 0) Painter.SetButtonEnabledStatus(PlaceBox, Keys.BAT1PLBTN, false);
                    break;

                case CustomDefines.SHIP_BATTLESHIP:
                    Pl_BattleshipsLeft--;
                    if (Pl_BattleshipsLeft == 0) Painter.SetButtonEnabledStatus(PlaceBox, Keys.BAT2PLBTN, false);
                    break;

                case CustomDefines.SHIP_CRUISER:
                    Pl_CruisersLeft--;
                    if (Pl_CruisersLeft == 0) Painter.SetButtonEnabledStatus(PlaceBox, Keys.BAT3PLBTN, false);
                    break;

                case CustomDefines.SHIP_DESTROYER:
                    Pl_DestroyersLeft--;
                    if (Pl_DestroyersLeft == 0) Painter.SetButtonEnabledStatus(PlaceBox, Keys.BAT4PLBTN, false);
                    break;

                case CustomDefines.SHIP_SUBMARINE:
                    Pl_SubmarinesLeft--;
                    if (Pl_SubmarinesLeft == 0) Painter.SetButtonEnabledStatus(PlaceBox, Keys.BAT5PLBTN, false);
                    break;
            }
        }
        //-------------------------------------------------------------------------------------------------------------------
        private int CountShipsLeft(int _type)
        {
            int count = 0;
            switch (_type)
            {
                case CustomDefines.SHIP_CARRIER:
                    count = Pl_CarriersLeft;
                    break;
                case CustomDefines.SHIP_BATTLESHIP:
                    count = Pl_BattleshipsLeft;
                    break;
                case CustomDefines.SHIP_CRUISER:
                    count = Pl_CruisersLeft;
                    break;
                case CustomDefines.SHIP_DESTROYER:
                    count = Pl_DestroyersLeft;
                    break;
                case CustomDefines.SHIP_SUBMARINE:
                    count = Pl_SubmarinesLeft;
                    break;
            }
            return count;
        }
        //-------------------------------------------------------------------------------------------------------------------
        /*
        private void square_MouseLeftButtonDown(object sender, MouseEventArgs e)
        {
            
            SquareProperties sprop = new SquareProperties();
            sprop = (SquareProperties)(((Rectangle)sender).Tag);

            switch(CurrentGameMode)
            {
                case CustomDefines.GAMEMODE_INACTIVE:
                {
                    MessageBox.Show("Start a new game first");
                    break;
                }
                case CustomDefines.GAMEMODE_ACTIVE_PLACEMENT:
                {

                    if (comboBox1.SelectedIndex != -1)
                    {
                        //ComboBoxItem cbi = (ComboBoxItem)comboBox1.SelectedItem;
                        String sLength = comboBox1.SelectedValue.ToString();
                        CurrShipSize = Int32.Parse(sLength);

                        MessageBox.Show("MODE = PLACEMENT");
                    }



                    break;
                }
                case CustomDefines.GAMEMODE_ACTIVE_PLAYFIRE:
                {

                    MessageBox.Show("MODE = JEU");


                    break;
                }

            }

            //MessageBox.Show(String.Format("Player = {0}, CoordX = {1}, CoordY = {2}", sprop.Player, CustomDefines.TabLettres[sprop.X].ToString(), (sprop.Y + 1).ToString()));
        }
        
        */
        //-------------------------------------------------------------------------------------------------------------------
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //MessageBox.Show("Current size: width =  " + this.Width + " et height = " + this.Height);
        }
        //-------------------------------------------------------------------------------------------------------------------
        public void InitGame(int gt, int rl, int po, String ipaddr)
        {
            Painter.SetGameContentVisibility(AbstractGrid, GeneralViewBox, true);

            // Début placement navires
            CurrentGameMode = CustomDefines.GAMEMODE_ACTIVE_PLACEMENT;
            Painter.InitCommandsPanel(CustomDefines.DRAW_COMMANDS_PLACEMENT, this.placingBtnsClick, PlayBox, PlaceBox);
            Painter.UpdateAmountsLabels(PlaceBox, Pl_CarriersLeft, Pl_BattleshipsLeft, Pl_CruisersLeft, Pl_DestroyersLeft, Pl_SubmarinesLeft, minesLeft);

            if (gt == CustomDefines.GAME_SINGLEPLAYER)
            {
                PlacedShip.InitPlacedShipTab(PlayerShips, CustomDefines.PLAYER_HUMAN);
                PlacedShip.InitPlacedShipTab(AIShips, CustomDefines.PLAYER_AI);
            }
            else
            { } // Multiplayer case, not implemented

            gameType = gt;
            multi_role = rl;
            multi_port = po;
            multi_ip = ipaddr;
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void button3_Click(object sender, RoutedEventArgs e)
        {

            XmlDocument xmlDoc = new XmlDocument();


            // Write down the XML declaration
            XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);

            // Create the root element
            XmlElement rootNode = xmlDoc.CreateElement("CategoryList");
            xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement);
            xmlDoc.AppendChild(rootNode);

            // Create a new <Category> element and add it to the root node
            XmlElement parentNode = xmlDoc.CreateElement("Category");

            // Set attribute name and value!
            parentNode.SetAttribute("ID", "01");

            xmlDoc.DocumentElement.PrependChild(parentNode);

            // Create the required nodes
            XmlElement mainNode = xmlDoc.CreateElement("MainCategory");
            XmlElement descNode = xmlDoc.CreateElement("Description");
            XmlElement activeNode = xmlDoc.CreateElement("Active");

            // retrieve the text 
            XmlText categoryText = xmlDoc.CreateTextNode("XML");
            XmlText descText = xmlDoc.CreateTextNode("This is a list my XML articles.");
            XmlText activeText = xmlDoc.CreateTextNode("true");

            // append the nodes to the parentNode without the value
            parentNode.AppendChild(mainNode);
            parentNode.AppendChild(descNode);
            parentNode.AppendChild(activeNode);

            // save the value of the fields into the nodes
            mainNode.AppendChild(categoryText);
            descNode.AppendChild(descText);
            activeNode.AppendChild(activeText);

            // Save to the XML file
            xmlDoc.Save("categories.xml");



           
        }
        //-------------------------------------------------------------------------------------------------------------------
       
        private void connect_Click(object sender, RoutedEventArgs e)
        {
            this.PWin = new PlayersWindow(this);
            PWin.Show();
        }
        //--------------------------------------------------------------------------------------------------------------------------------------------
        private void disconnect_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("Do you really want to disconnect ?", "Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
            {
                Painter.SetGameContentVisibility(this.AbstractGrid, this.GeneralViewBox, false);
                this.itemConnect.IsEnabled = true;
                this.itemDisconnect.IsEnabled = false;
                this.itemNewGame.IsEnabled = false;
                this.itemOpenGame.IsEnabled = false;
                this.itemDeleteGame.IsEnabled = false;
                this.itemEditPlayer.IsEnabled = false;
                this.itemLoadPlayer.IsEnabled = false;
                this.itemRemovePlayer.IsEnabled = false;
            }

        }
        //--------------------------------------------------------------------------------------------------------------------------------------------
    }
}
